<template>
  <div class="login-way">
    <el-form :model="loginWayForm">
      <el-form-item>
        <el-input v-model="loginWayForm.username" placeholder="请输用户名" />
      </el-form-item>
      <el-form-item class="password-item">
        <el-input v-model="loginWayForm.password" placeholder="请输入密码" show-password />
      </el-form-item>
    </el-form>
    <div class="login-btn" @click="handleLoginClick">
      登陆
    </div>
  </div>
</template>
<script>
import { mapMutations } from 'vuex'
import { userLogin, getUserInfo } from 'api/user.js'
import { ERR_OK } from 'api/config.js'
export default {
  data () {
    return {
      loginWayForm: {
        username: '',
        password: '',
      }
    }
  },
  methods: {
    // 登录
    handleLoginClick () {
      userLogin(this.loginWayForm).then(res => {
        let { code, data } = res
        if (code == ERR_OK) {
          this.$message.success('登录成功');
          this.setToken(data.token)

          // 获取用户信息
          getUserInfo().then(r => {
            if (r.code == ERR_OK) {
              this.setUserInfo(r.data)
              this.setShowLogin(false)
            } else {
              this.$message.error('获取用户信息失败')
              this.setToken('')
              this.setUserInfo({})
            }
          })
        } else {
          this.$message.error('登录失败')
          this.setToken('')
          this.setUserInfo({})
        }
      })
    },
    // vuex
    ...mapMutations('login', {
      'setUserInfo': 'SET_USER_INFO',
      'setToken': 'SET_TOKEN',
      'setShowLogin': 'SET_SHOW_LOGIN'
    })
  }
}
</script>
<style lang="stylus" scoped>
  @import '~assets/stylus/login-form.styl';
</style>
